package com.dhh.activity;

import java.util.ArrayList;
import java.util.List;
import com.dhh.R;
import com.dhh.dao.DataBaseHelper;
import com.dhh.util.CUtil;
import com.dhh.util.Constant;
import com.dhh.util.manager.DietManager;
import com.dhh.util.manager.PlanManager;
import com.dhh.vo.FoodDiet;
import com.dhh.widget.AmazingAdapter;
import com.dhh.widget.AmazingListView;
import greendroid.app.GDActivity;
import greendroid.widget.ActionBarItem.Type;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Pair;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.TextView;

public class DietLogActivity extends GDActivity{
	private DataBaseHelper db;
	private DietManager dManager;
	private PlanManager pManager;
	private AmazingListView lsComposer;
	private SectionComposerAdapter adapter;
	private ProgressDialog progressDialog;
	private String cItemId;

	@Override  
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
		setActionBarContentView(R.layout.diet_log);
		
        db = new DataBaseHelper(getBaseContext());
        db.openDataBase();         
        dManager = new DietManager(db);
        pManager = new PlanManager(db);
        
		initActionBar();
		initView();
	}
	
	@Override
	public void onStart() {
        super.onStart();     
        initData();
	}
	
	@Override
    public void onResume(){
    	super.onResume();
        db.openDataBase();       
        if(progressDialog!=null) 
        	progressDialog.dismiss();
    }
    
    @Override
	protected void onPause(){
		super.onPause();
		if (db != null) {
			db.close();
		}
	}
    
    @Override
	protected void onStop(){
		super.onStop();
	}
	
	private void initData(){
		adapter = new SectionComposerAdapter();
		List<Pair<String, List<FoodDiet>>> logs = new ArrayList<Pair<String, List<FoodDiet>>>();
		Pair<String, List<FoodDiet>> pair = new Pair<String, List<FoodDiet>>("",dManager.getAllDiet());
		logs.add(pair);
		adapter.setData(logs);
		
		if(adapter.getCount()==0){
			lsComposer.setVisibility(View.GONE);
		}else{
			lsComposer.setVisibility(View.VISIBLE);
			lsComposer.setAdapter(adapter);
			lsComposer.setOnItemClickListener(new OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id){
					TextView did = (TextView) view.findViewById(R.id.dl_identify);
					Intent intent = new Intent(DietLogActivity.this,DietDesignActivity.class);
					intent.putExtra(Constant.C_DIET_ID, did.getText().toString());
					startActivity(intent);
				}			
			});
			lsComposer.setOnItemLongClickListener(new OnItemLongClickListener() {
				@Override
				public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
					cItemId = ((TextView)view.findViewById(R.id.dl_identify)).getText().toString();		
					DietLogActivity.this.showDialog(1);
					return true;
				}
			});
		}
	}
	
	private void initActionBar(){
		getActionBar().setTitle(" My Recipe");
        getActionBar().setBackgroundColor(Color.rgb(14, 166, 249));
        getActionBar().getChildAt(0).
        	setOnClickListener(new OnClickListener(){
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(DietLogActivity.this,HomeActivity.class);	
					startActivity(intent);
				}}); 
        addActionBarItem(Type.Add).getItemView()
                .setOnClickListener(new OnClickListener(){
					@Override
					public void onClick(View v) {
						getAlertDialogTextEdit("Please input the diet name:").show();
					}}); 
	}
	
	private void initView(){
		lsComposer = (AmazingListView) findViewById(R.id.flComposer);    
        lsComposer.setTextFilterEnabled(true);
		lsComposer.setDivider( null );
		lsComposer.setDividerHeight(1); 
	}
	
	class SectionComposerAdapter extends AmazingAdapter {
		List<Pair<String, List<FoodDiet>>> all = null;
		
		public void setData(List<Pair<String, List<FoodDiet>>> data){
			all = data;
		}

		@Override
		public int getCount() {
			int res = 0;
			for (int i = 0; i < all.size(); i++) {
				res += all.get(i).second.size();
			}
			return res;
		}

		@Override
		public FoodDiet getItem(int position) {
			int c = 0;
			for(int i = 0; i < all.size(); i++) {
				if(position >= c && position < c + all.get(i).second.size()) {
					return all.get(i).second.get(position - c);
				}
				c += all.get(i).second.size();
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		protected void onNextPageRequested(int page) {
		}

		@Override
		protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
			view.findViewById(R.id.header).setVisibility(View.GONE);
		}

		@Override
		public View getAmazingView(int position, View convertView, ViewGroup parent) {
			View res = convertView;
			if (res == null) res = getLayoutInflater().inflate(R.layout.diet_log_item, null);
			TextView date = (TextView) res.findViewById(R.id.dl_date);
			TextView name = (TextView) res.findViewById(R.id.dl_name);
			TextView ld = (TextView) res.findViewById(R.id.dl_identify);
			
			FoodDiet item = getItem(position);
			date.setText(CUtil.getDate("yyyy-MM-dd", "EEE,MMM dd", item.getDate()));
			ld.setText(item.getId());
			name.setText(item.getName());
			
			return res;
		}

		@Override
		public void configurePinnedHeader(View header, int position, int alpha) {
			TextView lSectionHeader = (TextView)header;
			lSectionHeader.setText(getSections()[getSectionForPosition(position)]);
			lSectionHeader.setBackgroundColor(alpha << 24 | (0xbbffbb));
			lSectionHeader.setTextColor(alpha << 24 | (0x000000));
		}
		

		@Override
		public int getPositionForSection(int section) {
			if (section < 0) section = 0;
			if (section >= all.size()) section = all.size() - 1;
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (section == i) { 
					return c;
				}
				c += all.get(i).second.size();
			}
			return 0;
		}

		@Override
		public int getSectionForPosition(int position) {
			int c = 0;
			for (int i = 0; i < all.size(); i++) {
				if (position >= c && position < c + all.get(i).second.size()) {
					return i;
				}
				c += all.get(i).second.size();
			}
			return -1;
		}

		@Override
		public String[] getSections() {
			String[] res = new String[all.size()];
			for (int i = 0; i < all.size(); i++) {
				res[i] = all.get(i).first;
			}
			return res;
		}
		
	}
	
	AlertDialog getAlertDialogTextEdit(String title){
		final FrameLayout fl = new FrameLayout(DietLogActivity.this);
		final EditText input = new EditText(DietLogActivity.this);
		input.setGravity(Gravity.CENTER);
		fl.addView(input, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT));
		input.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
		
		AlertDialog.Builder builder = new AlertDialog.Builder(DietLogActivity.this);
		builder.setView(fl).setTitle(title).
			setPositiveButton("OK", new DialogInterface.OnClickListener(){		    	 
                @Override
                public void onClick(DialogInterface d, int which) {    
        			SearchThread thread = new SearchThread(input.getText().toString(),pManager.getCurrentPlanSimple().getId());
        			thread.start();
                	DietLogActivity.this.showDialog(0);
                	d.dismiss();
                }
		    }).
		    setNegativeButton("Cancel", new DialogInterface.OnClickListener(){		    	 
                @Override
                public void onClick(DialogInterface d, int which) {
                	d.dismiss();
                }
		    });
		
		return builder.create();
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch(id){
			case 0:
				progressDialog = new ProgressDialog(this);
				progressDialog.setTitle("Creating diet...");
				progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				return progressDialog;			
			case 1:
				return new AlertDialog.Builder(this)
				.setIcon(android.R.drawable.ic_dialog_alert)
				.setTitle("Are you sure you want to delete this diet?")
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,	int whichButton){
							pManager.removePlanItemByParent(cItemId);
							dManager.deleteDiet(cItemId);
							initData();	
							Toast.makeText(getBaseContext(),"The diet has been deleted!", Toast.LENGTH_SHORT).show();
						}
					}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,int whichButton){
							}
						}).create();
		}
		
		return null;		
	}
	
	private class SearchThread extends Thread {
		String title;
		String planId;
		FoodDiet rdiet;
		
		public SearchThread(String title,String planId){
			this.title = title;
			this.planId = planId;
		}		

        @Override
        public void run() {         
            FoodDiet diet = new FoodDiet();
            diet.setName(title);
            diet.setPlanId(planId);
            diet.setDate(CUtil.getToday());
            rdiet =  dManager.addDiet(diet);
            handler.sendEmptyMessage(0);
        }

        private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
            	Intent intent = new Intent(DietLogActivity.this,DietDesignActivity.class);
            	String did = rdiet.getId();
				intent.putExtra(Constant.C_DIET_ID,did);
				startActivity(intent);
            }
        };
    }
}
